<template>
    <!-- 操作按钮区 -->
    <div class="action-buttons">
        <el-button type="primary" @click="batchSaveDetails">添加</el-button>
        <el-button @click="handleDataArchive">数据暂存</el-button>
        <el-button @click="handleImport">导入</el-button>
    </div>

    <div>
        <!-- 查询条件部分 -->
        <div class="search-section">
            <el-form :inline="true" :model="prolist">
                <el-form-item label="退料编号">
                    <el-input v-model="prolist.subject" placeholder="输入退料编号"></el-input>
                </el-form-item>
                <el-form-item label="退料主题">
                    <el-input v-model="prolist.documentNumber" placeholder="输入退料主题"></el-input>
                </el-form-item>

                <el-form-item label="添加人员">
                    <el-input v-model="prolist.operatorName" placeholder="输入添加人员"></el-input>
                </el-form-item>
                <el-form-item label="退料日期">
                    <el-date-picker v-model="prolist.startDate" type="date" placeholder="选择开始日期"></el-date-picker>
                    -
                    <el-date-picker v-model="prolist.endDate" type="date" placeholder="选择结束日期"></el-date-picker>
                </el-form-item>

                <el-form-item label="入库状态">
                    <el-select v-model="prolist.storageStatus" placeholder="请选择入库状态">
                        <el-option v-for="option in storageStatusOptions" :key="option.value" :label="option.label" :value="option.value">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item>
                    <el-button @click="ShowMaterials">查询</el-button>
                </el-form-item>
            </el-form>
        </div>

        <div class="page-title">
            <h2>物料清单列表</h2>
        </div>
        <!-- 生产计划列表（仅展示序号列相关结构） -->
        <div class="table-container">

            <el-table :data="planList" stripe ref="tableRef">
                <el-table-column type="selection"></el-table-column>
                <el-table-column prop="strippingId" label="主键"></el-table-column>
                <el-table-column prop="subject" label="生产退料编号"></el-table-column>
                <el-table-column prop="documentNumber" label="生产退料主题"></el-table-column>
                <el-table-column prop="returndate" label="退料日期">
                    <template #default="scope">
                        {{ formatDate(scope.row.returndate) }}
                    </template>
                </el-table-column>
                <el-table-column prop="operatorName" label="制单人员"></el-table-column>
                <!-- <el-table-column prop="bomSubject" label="退料数量"></el-table-column> -->
               <el-table :data="tableData">
                    <el-table-column prop="documentNo" label="入库状态">
                     
                    </el-table-column>
                </el-table>


                <el-table-column prop="right" label="操作">
                    <template #default="scope">
                        <el-button type="text" @click="GetBYIdProductionPlanning(scope.row.strippingId)">关联项目反填</el-button>
                        <el-button type="text" @click="DeleteProductionPlanning(scope.row.strippingId)">删除</el-button>
                         <el-button type="text" @click="StockInApplication(scope.row.strippingId)">申请入库</el-button>
                    </template>
                    
                </el-table-column>
            </el-table>
            <!-- 分页部分 -->
<!-- 
            <el-button @click="batchDelete">批量删除</el-button> -->
        </div>
        <div style="margin-top: 20px">
            <el-pagination
                    v-model:current-page="page.pageindex"
                    v-model:page-size="page.pageSize"
                    :page-sizes="[5, 20, 25, 30]"
                    :background="true"
                    prev-text="上一页"
                    next-text="下一页"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total.totalCount"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
            />
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { Materialread, Materialwrite  } from '@/axios/axiosHelper';
import { ElMessage, ElMessageBox } from 'element-plus';
import router from '@/router';
import axios from 'axios';

// 定义搜索表单数据
const prolist = ref({
    subject: '',
    documentNumber: '',
    startDate: '',
    endDate: '',
    operatorName: '',
    storageStatus: 'all' // 初始化入库状态，这里设为“全部”，可按需调整
});

// 定义分页总数
const total = ref({
    totalCount: 0,
    pageCount: 0,
});
// 定义分页对象
const page = ref({
    pageindex: 1,
    pageSize: 15,
});

// 模拟生产计划列表数据
const planList = ref([
    {
        "strippingId": '',
        "subject": "",
        "documentNumber": "",
        "returndate": "",
        "operatorName": "",
        "remark": "",
    }
]);

    const storageStatusOptions = ref([
      { value: 'all', label: '全部' },
      { value: 'not_applied', label: '未申请入库' },
      { value: 'partially_applied', label: '部分申请入库' },
      { value: 'applied_not_stored', label: '申请完毕 未入库' },
      { value:'stored', label: '入库完毕' },
      { value: 'applied_partially_stored', label: '申请完毕 部分入库' }
    ]);
    const getStatusLabel = (statusValue) => {
      const option = storageStatusOptions.value.find(opt => opt.value === statusValue);
      return option? option.label : '';
    };



const formatDate = (dateStr) => {
    const date = new Date(dateStr);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hour = String(date.getHours()).padStart(2, '0');
    const minute = String(date.getMinutes()).padStart(2, '0');
    const second = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
};

// 表格引用
const tableRef = ref(null);

// 全选状态
const allChecked = ref(false);

// 选中的 ID 列表
const checkedIds = ref([]);

const ShowMaterials = () => {
    Materialread.get("/l-read/api/GStripping/GetStripping", {
        params: {
            pageindex: page.value.pageindex,
            pageSize: page.value.pageSize,
            subject: prolist.value.subject,
            documentNumber: prolist.value.documentNumber,
            startDate: prolist.value.startDate,
            endDate: prolist.value.endDate,
            operatorName: prolist.value.operatorName,
            storageStatus: prolist.value.storageStatus
        }
    }).then((res) => {
        // 校验数据结构
        if (res.data && typeof res.data === 'object' && res.data.data && typeof res.data.data === 'object') {
            planList.value = res.data.data.result;
            console.log("显示数据", res.data.data);

            total.value.totalCount = res.data.data.totalCount;
            total.value.pageCount = res.data.data.pageCount;
            // 重置全选状态和选中的 ID 列表
            allChecked.value = false;
            checkedIds.value = [];
            console.log(res.data.data);
        } else {
            console.error('接口返回数据结构异常');
            ElMessage.error('数据获取失败，请稍后重试');
        }
    }).catch((error) => {
        console.error('接口请求失败:', error);
        ElMessage.error('数据获取失败，请稍后重试');
    });
};

// 编辑跳转修改
const GetBYIdProductionPlanning = (strippingId) => {
    router.push({
        path: 'FTZStripping',
        query: {
            strippingId: strippingId
        }
    });
    console.log(strippingId);
};

// 跳转添加
const batchSaveDetails = (strippingId) => {
    router.push({
        name: 'AddStripping',
    });
};
const StockInApplication = (strippingId)=>{
     router.push({
        path: 'AddStockInApplication',
        query: {
            strippingId: strippingId
        }
    });
    console.log(strippingId);
}

// 数据暂存
const handleDataArchive = () => {
    // 这里可以添加数据暂存的逻辑
    ElMessage.warning('数据暂存功能待实现');
};

// 导入
const handleImport = () => {
    Materialread.get("/l-read/api/GetValues/ExportToExcel").then((res) => {
        ElMessage.success('导入成功');
    }).catch((error) => {
        console.error('导入失败:', error);
        ElMessage.error('导入失败，请稍后重试');
    });
};

// 删除单条记录
const DeleteProductionPlanning = async (strippingId) => {
    try {
        const confirmResult = await ElMessageBox.confirm(
            '确认删除该条记录？',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        );
        if (confirmResult === 'confirm') {
            const response = await axios.delete(
                `https://localhost:7077/api/Stripping/DelStripping`,
                {
                    params: { StrippingId: strippingId.toString() }
                }
            );
            if (response.data.code === 300) {
                ElMessage.success('删除成功');
                ShowMaterials(); // 调用 ShowMaterials 方法刷新数据
            } else {
                ElMessage.error(`删除失败：${response.data.message}`);
            }
        }
    } catch (error) {
        if (error!== 'cancel') {
            console.error('删除错误:', error);
            ElMessage.error('删除失败，请检查网络或联系管理员');
        }
    }
};

// 处理全选
// const handleCheckAllChange = (value) => {
//     if (value) {
//         checkedIds.value = planList.value.map(item => item.StrippingId);
//     } else {
//         checkedIds.value = [];
//     }
//     allChecked.value = value;
// };

// // 批量删除
// const batchDelete = async () => {
//     if (checkedIds.value.length === 0) {
//         ElMessage.warning('请选择要删除的记录');
//         return;
//     }
//     try {
//         const confirmResult = await ElMessageBox.confirm(
//             '确认删除选中的记录？',
//             '提示',
//             {
//                 confirmButtonText: '确定',
//                 cancelButtonText: '取消',
//                 type: 'warning'
//             }
//         );
//         if (confirmResult === 'confirm') {
//             const ids = checkedIds.value.join(',');
//             const response = await Materialwrite.delete(
//                 `/l-write/api/Ment/DelMaterials`,
//                 {
//                     params: { bomid: ids }
//                 }
//             );
//             if (response.data.code === 200) {
//                 ElMessage.success('批量删除成功');
//                 ShowMaterials(); // 调用 ShowMaterials 方法刷新数据
//             } else {
//                 ElMessage.error(`批量删除失败：${response.data.message}`);
//             }
//         }
//     } catch (error) {
//         if (error!== 'cancel') {
//             console.error('批量删除错误:', error);
//             ElMessage.error('批量删除失败，请检查网络或联系管理员');
//         }
//     }
// };

const handleSizeChange = (val) => {
    page.value.pageSize = val;
    ShowMaterials();
};

const handleCurrentChange = (val) => {
    page.value.pageindex = val;
    ShowMaterials();
};

onMounted(() => {
    ShowMaterials();
    getStatusLabel();
});
</script>

<style scoped>
.search-section {
    margin-bottom: 20px;
}

.table-container {
    max-height: 400px; /* 固定表格最大高度 */
    overflow-y: auto; /* 超出高度显示滚动条 */
    margin-bottom: 20px; /* 为分页预留空间 */
}

.el-table {
    width: 100%; /* 表格宽度占满容器 */
}
</style>    